#!/usr/bin/env bash
set -e
# Getting this value out of Autoconf is not a good idea, because it might be
# set to a relative path to install-sh.  We don't install `install-sh' during
# `make install' anyway, so...  See bug #74.
MKDIR_P='mkdir -p'
MD5="@MD5@"
WGET="@WGET@"
CURL="@CURL@"
# The ".." is because we need to go out of the build-aux directory.
srcdir="@abs_srcdir@/.."

f=`basename "$2"`
d=`dirname "$2"`

validate_checksum() {
  cksum=`$MD5 "$1" | sed 's/.*\([0-9a-fA-F]\{32\}\).*/\1/'`
  valid=`< "$srcdir/${1%-t}.md5"`
  test "x$cksum" = "x$valid"
}

# Don't re-download if we happen to have the right file already.
test -f "$2" && validate_checksum "$2" && touch "$2" && exit

rm -f "$2"
$MKDIR_P "$d"
# Make sure we clean up after ourselves when we exit.
trap "rv=\$?; rm -f '$2-t'; exit \$rv" 0

if test -n "$WGET"; then
  $WGET "$1/$f" -O "$2-t"
elif test -n "$CURL"; then
  $CURL "$1/$f" -o "$2-t"
else
  echo >&2 "cannot find a tool to download $1/$f"
  exit 1
fi

if validate_checksum "$2-t"; then
  mv "$2-t" "$2"
  # wget sets the timestamp to whatever is the Last-Modified header, so
  # make sure we have a recent mtime on the file to keep `make' happy.
  touch "$2"
else
  echo >&2 "error: invalid checksum for $2"
  echo >&2 "error: expected: $valid"
  echo >&2 "error:    found: $cksum"
  exit 1
fi
